package com.intellagric.agriecom.controller.agriecom_index;


import com.intellagric.agriecom.module.agriecom_produce.ProduceService;
import com.intellagric.common.pojo.LayuiDataGridResult;
import com.intellagric.common.utils.UUIDUtils;
import com.intellagric.pojo.AgriecomProduce;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.Date;

@Controller
public class GrabDataController {

    @Autowired
    private ProduceService produceService;

    @RequestMapping("/index/grabData")
    @ResponseBody
    public String grabData(String fruitName,String categoryId){
        System.out.println(fruitName);
        System.out.println(categoryId);

        for(int i =1;i<2;i++) {
            //获取url
            String url = "http://www.cnhnb.com/p/"+fruitName+"-0-0-0-0-"+i+"/";
            //爬取网页信息
            String html = pickData(url);
            //获取html中的内容
            Document document = Jsoup.parse(html);
            //获取html class 为product-content-ul 的节点
            Elements divs = document.getElementsByClass("product-bg");


            for(Element e :divs){
                AgriecomProduce p=new AgriecomProduce();

                p.setProduceId(UUIDUtils.getID());
                //categoryId分类
                p.setCategoryId(categoryId);

                //显示一张图片
                Elements imgEle=  e.select("img.s-image");
                String img=imgEle.get(0).attr("src")+",";
                p.setProduceImg(img);

                e=e.selectFirst("#fruit-text");
                //产品名称
                Element nameEle=  e.selectFirst("span.fruit-explain");
                String name=nameEle.text();
                p.setProduceName(name);

                //单位
                Elements unitEle=  e.select("li span.Jin");
                String unit=unitEle.get(0).text();
                p.setUnit(unit);
                //价格
                Elements priceEle=  e.select("li span.fruit-price");
                String price=priceEle.get(0).text();
                p.setPrice(Float.parseFloat(price));
                //producingArea产地
                Elements placeEle=  e.select("li span.place");
                String producingArea=placeEle.get(1).text();
                p.setProducingArea(producingArea);
                //商家名称


                //进去产品详情页面，再抓取数据

                //商品编号
                Elements proIdEle=  e.select("a.seller");
                String proId=proIdEle.get(0).attr("href");
                String urlPro = "http://www.cnhnb.com"+proId;
                //爬取网页信息
                String htmlPro = pickData(urlPro);
                //获取html中的内容
                Document documentPro = Jsoup.parse(htmlPro);


                //图片区
                Elements imgUl = documentPro.getElementsByClass("ul.clearfix");
                //图片完善
                Elements imgEles=  imgUl.select("img.s-image");
                for(int j=1;j<imgEles.size();j++) {
                    String imgUrl = imgEles.get(j).attr("src");
                    String imgs=p.getProduceImg();
                    imgs+=imgUrl+",";
                    p.setProduceImg(imgs);
                }

//                //库存
//                Elements imgEle=  e.select("img .s-image");
//                String img=imgEle.get(0).attr("src");
//                p.setProduceImg(img);

//                //简述
//                Elements imgEle=  e.select("detail-info");
//                String img=imgEle.get(0).attr("src");
//                p.setProduceBrief(img);


                //商家id
                p.setMerchantId("773d6c9b959948e2bb70996967e4c7f2");
                //溯源码
                p.setSourceCode("12a1673e29e641d4bb01768eec8ae996");
                //createDate、updateDate
                p.setCreateDate(new Date());
                p.setUpdateDate(new Date());
                //produceDesc
                Elements descEle=  documentPro.select("div.detail-info");
                p.setProduceDesc(descEle.get(0).toString());
                //参数
                Elements paramEle= descEle.get(0).select(".eye-renderer__float");
                String params="";
                for(Element y:paramEle){
                    Elements span= y.select("span");
                    String paramName=span.get(0).text();
                    String paramValue=span.get(1).text();
                    params+=paramName+""+paramValue+"；";
                }
                if(params.length()>1)
                params=params.substring(0,params.length()-2);//切掉最后的；
                p.setProduceParameter(params);
//                System.out.println(produceService);
                produceService.insertProduce(p);

            }

        }

        return "1111";
    }
    /*
     * 爬取网页信息
     */
    private static String pickData(String url) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpget = new HttpGet(url);
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                // 打印响应状态
                if (entity != null) {
                    return EntityUtils.toString(entity);
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        }  catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
